<template>
  <div class="edit-warp">
    <el-form ref="ruleForm" :rules="rules" :model="form" :label-position="'top'" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('configLazyLoad.channel.appletName')" prop="name">
            <el-input v-model.trim="form.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('configLazyLoad.channel.wexinAPPTip12')" prop="appid">
            <el-input v-model.trim="form.appid" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('configLazyLoad.channel.wexinAPPTip13')" prop="appSecret">
            <el-input v-model.trim="form.appSecret"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item :label="$t('configLazyLoad.channel.wexinAPPTip14')" prop="access_token_url">
            <el-input v-model.trim="form.access_token_url"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <question-tooltip class="wechatTootip" :direction="'bottom'" :tipContent="$t('configLazyLoad.channel.wexinAPPTip15')"></question-tooltip>
        </el-col>
        <el-col :span="24" v-show="configType === 'config'">
          <el-form-item :label="$t('configLazyLoad.channel.useSche')">
            <el-radio-group v-model.trim="form.scheduleEnable">
              <el-radio :label="false">{{$t('configLazyLoad.public.noReuse')}}</el-radio>
              <el-radio :label="true">{{$t('configLazyLoad.public.reuse')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <p class="remark" style="margin-bottom: 5px">{{$t('configLazyLoad.channel.wexinTip23')}}</p>
        </el-col>

        <el-col :span="configType === 'config' ? 10 : 22">
          <el-form-item :label="$t('configLazyLoad.channel.turnTip3')">
            <el-radio-group v-model.trim="form.openTriggerWord">
              <el-radio :label="false">{{$t('public.no')}}</el-radio>
              <el-radio :label="true">{{$t('public.yes')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col  :span="2">
          <question-tooltip class="wechatTootip" :direction="'bottom'" :tipContent="$t('configLazyLoad.channel.turnTip4')"></question-tooltip>
        </el-col>

        <el-col :span="configType === 'config' ? 10 : 22">
          <el-form-item :label="$t('config.channel.userPeopleWord')" prop="convert_words">
            <el-input size="mini" v-model.trim="form.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
          </el-form-item>
        </el-col>
        <el-col  :span="2">
          <question-tooltip class="wechatTootip" :direction="'bottom'" :tipContent="$t('configLazyLoad.channel.turnTip6')"></question-tooltip>
        </el-col>
        <el-col :span="22">
          <el-form-item :label="$t('configLazyLoad.channel.wexinTip104')" prop="server_url">
            <el-input v-model.trim="form.server_url" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-tooltip :content="$t('public.copy')" placement="bottom">
            <i class="quickRe iconfont icon-fuzhi" @click="copy('server_url')"></i>
          </el-tooltip>
        </el-col>
        <el-col :span="22">
          <el-form-item :label="$t('configLazyLoad.channel.wexinTip106')" prop="token">
            <el-input v-model.trim="form.token" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-tooltip :content="$t('public.copy')" placement="bottom">
            <i class="quickRe iconfont icon-fuzhi" @click="copy('token')"></i>
          </el-tooltip>
        </el-col>
        <el-col :span="22">
          <el-form-item label="EncodingAESKey" prop="encoding_AESKey">
            <el-input v-model.trim="form.encoding_AESKey" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-tooltip :content="$t('public.copy')" placement="bottom">
            <i class="quickRe iconfont icon-fuzhi" @click="copy('encoding_AESKey')"></i>
          </el-tooltip>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="!form.scheduleEnable"  :label="$t('config.channel.isUseRobt')" prop="robot">
            <el-select style="width: 100%" size="mini" v-model.trim="form.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
              <el-option value="">{{$t('public.pleasePick')}}</el-option>
              <el-option
                v-for="item in allrobotOptions"
                :key="item._id"
                :label="item.robot_name_new"
                :disabled="item.disabled"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-show="!form.scheduleEnable && aiRobots.length > 0"  :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId">
            <el-select style="width: 100%" size="mini" v-model.trim="form.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
              <el-option value="">{{$t('public.pleasePick')}}</el-option>
              <el-option
                v-for="item in aiRobots"
                :key="item._id"
                :label="item.robot_name_new"
                :disabled="item.disabled"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item v-if="!form.scheduleEnable" :label="$t('configLazyLoad.interfaceConfig.msgGroup')" prop="to_peer">
            <el-select style="width: 100%" size="mini" v-model.trim="form.to_peer" :placeholder="$t('public.pleasePick')">
              <el-option
                v-for="(item, index) in peerOptions"
                :key="index"
                :label="item.DisplayName"
                :value="item.Exten">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-show="!form.scheduleEnable" :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime">
            <el-radio-group v-model="form.welcomePushTime" @change="pushTimeChange">
              <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
              <el-radio class="radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item v-show="!form.scheduleEnable"  :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
            <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
            <question-tooltip
                    class="weiboTooltip"
                    :direction="'bottom'"
                    :tipContent="$t('configLazyLoad.channel.webStyleTip6')">
            </question-tooltip>
            <div class="placeholder_box">
              <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
                {{place.content}}
                <i class="iconfont icon-zhankai"></i>
              </dl>
            </div>
            <el-input size="mini" type="textarea" v-model="form.welcome_msg"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('config.channel.isUseSatisfaction')" prop="csr">
            <el-radio class="radio" v-model.trim="form.webchat_csr" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
            <el-radio class="radio statis-radio" v-model.trim="form.webchat_csr" :label="true">{{$t('config.channel.enabled')}}</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" class="primary_btn fr" @click="onSubmit">{{$t('public.save')}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  import { deepClone } from '@/utils/m7Utils'
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import Clipboard from 'clipboard-js'
  export default {
    name: '',
    data () {
      return {
        form: {
          scheduleEnable: false
        },
        showTopeer: false,
        peerOptions: [],
        robotOptions: [],
        aiRobots: [],
        allrobotOptions: [],
        placeholderArr: [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ],
        rules: {
          name: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          appid: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          to_peer: [
            { required: true, message: this.$t('webchat.placeSkillsGrouop'), trigger: 'change' }
          ]
        }
      }
    },
    props: ['wechatConfigData'],
    components: {
      questionTooltip
    },
    computed: {
      configType () {
        let paths = this.$route.path.split('/')
        return paths[2]
      }
    },
    watch: {
      wechatConfigData () {
        this.initData()
      }
    },
    methods: {
      robotSelectShow (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.allrobotOptions
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.allrobotOptions = allRobot
            }
          })
        }
      },
      onSubmit () {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            let data = this.form
            if (!data.appSecret && !data.access_token_url) {
              this.$message.error(this.$t('configLazyLoad.channel.wexinAPPTip16'))
              return
            }
            if (!data.scheduleEnable) {
              if (data.robot === '') {
                data.robotType = ''
              } else {
                this.allrobotOptions.forEach((item) => {
                  if (item._id === data.robot) {
                    if (item.Nick) {
                      data.robotType = item.robotType
                    } else {
                      data.robotType = item.robot_type_new
                    }
                  }
                })
              }
  //          机器人辅助座席，增加assistRobotType参数
              this.aiRobots.map((item) => {
                if (data.robotAssistId === item._id) {
                  if (data.robotAssistId !== '') {
                    this.$set(data, 'assistRobotType', item.robotType)
                  } else {
                    this.$set(data, 'assistRobotType', '')
                  }
                }
              })
              data.robot = data.robot ? data.robot : ''
            }
            this.$store.dispatch('updateWeixinMiniConfigById', data).then((req) => {
              if (req.success) {
                this.$message.success(this.$t('configLazyLoad.channel.mailTip36'))
                this.$emit('submitEditOrAdd')
              }
            })
          }
        })
      },
      addPlaceholder (data) {
        this.form.welcome_msg += '{' + data + '}'
      },
      copy (type) {
        let self = this
        Clipboard.copy(this.form[type]).then(
          function () {
            self.$message.success(this.$t('config.business.copySuccess'))
          }
        )
      },
      //  更改欢迎语推送时机
      pushTimeChange (data) {
        if (data === 'access') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }
          ]
          let str = deepClone(this.form.welcome_msg)
          str = str.replace(/\{agent\}/g, '')
          str = str.replace(/\{agentName\}/g, '')
          this.form.welcome_msg = str
        } else if (data === 'claim') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }, {
              content: this.$t('configLazyLoad.channel.agent'),
              data: 'agent'
            }, {
              content: this.$t('configLazyLoad.channel.agentName'),
              data: 'agentName'
            }, {
              content: this.$t('configLazyLoad.channel.agentNickName'),
              data: 'agentNickName'
            }, {
              content: this.$t('configLazyLoad.channel.agentPhone'),
              data: 'agentPhone'
            }
          ]
        }
      },
      initData () {
        this.form = deepClone(this.wechatConfigData)
        this.pushTimeChange(this.form.welcomePushTime)
        if (!this.form.webchat_csr) {
          this.$set(this.form, 'webchat_csr', false)
        }
        if (!this.form.welcomePushTime) {
          this.$set(this.form, 'welcomePushTime', 'access')
        }
        if (!this.form.welcomeMsg) {
          this.$set(this.form, 'welcomeMsg', '')
        }
        if (!this.form.robot) {
          this.$set(this.form, 'robot', '')
        }
        if (!this.form.to_peer) {
          this.$set(this.form, 'to_peer', '')
        }
        if (!this.form.scheduleEnable) {
          this.$set(this.form, 'scheduleEnable', false)
        }
        if (!this.form.robotAssistId) {
          this.$set(this.form, 'robotAssistId', '')
        }
        if (this.form.openTriggerWord === undefined) {
          this.$set(this.form, 'openTriggerWord', true)
        }
        // 判断小七是否回显
        if (this.$store.state.isM7RobotOpen === false) {
          if (this.form.robot === '5825a500dfe52d5edc6e36c9') {
            this.form.robot = ''
          }
        }
      }
    },
    mounted () {
      this.initData()
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = this.$getCache('mailQueues')
        if (!mailQueues || mailQueues.length === 0) {
          return
        }
        this.peerOptions = mailQueues || []
      })
      this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
        let robotConfig = this.$getCache('robotConfig')
        this.robotOptions = robotConfig || []
        this.allrobotOptions = this.robotOptions
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            let configArr = []
            this.allrobotOptions.forEach((config) => {
              if (config.robot_type !== 'didi') {
                configArr.push(config)
              }
            })
            this.allrobotOptions = configArr.concat(this.aiRobots)
          }
        })
      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .edit-warp
    padding 20px
    .el-col-2
      color $c-main
      cursor pointer
      margin-top 26px
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
</style>
